package com.cxlin.base

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.cxlin.base.mvi.UiEvent
import com.cxlin.base.mvi.UiIntent
import com.cxlin.base.mvi.UiState
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus

/**
 *
 * @Author: chenxunlin
 * @Date: 2024/4/26 14:11
 */
abstract class BaseViewModel : ViewModel() {

    // 接收意图
    private val intentChannel = Channel<UiIntent>(Channel.UNLIMITED)// Channel.UNLIMITED 无限容量

    // 状态容器
    protected val mUiStateFlow = MutableStateFlow<UiState>(createInitState())
    val uiStateFlow: StateFlow<UiState> = mUiStateFlow

    // 事件容器
    protected val mEffectFlow = MutableSharedFlow<UiEvent>()
    val effectFlow: SharedFlow<UiEvent> = mEffectFlow


    init {
        // 注册意图接收
        viewModelScope.launch {
            intentChannel.consumeAsFlow().collect { value ->
                handleIntent(value)
            }
        }
    }

    fun sendIntent(intent: UiIntent){
        viewModelScope.launch {
            intentChannel.send(intent)
        }
    }
    protected abstract fun handleIntent(intent: UiIntent)

    protected abstract fun createInitState(): UiState

    fun registerEvent(){
        EventBus.getDefault().register(this)
    }

    fun unRegisterEvent(){
        EventBus.getDefault().unregister(this)
    }
}